<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<div style="padding: 10px">
    <h2>工单列表</h2>
    <div style="margin:20px 0;">
        <shiro:hasPermission name="order:find">
            <div style=" padding-bottom: 10px;">
                <form>
                    <label>
                        筛选支付状态：
                        <select id="search-paid" class="easyui-combobox" style="width:173px;">
                            <option value="">全部</option>
                            <option value="-1">未收</option>
                            <option value="0">清欠</option>
                        </select>
                    </label>
                    <label>
                        筛选工单状态：
                        <select id="search-order-status" class="easyui-combobox" style="width:173px;">
                            <option value="">全部</option>
                            <option value="0">未做</option>
                            <option value="1">在库</option>
                            <option value="2">完工</option>
                            <option value="3">已发</option>
                            <option value="4">以完成</option>
                        </select>
                    </label>
                    <label>
                        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitParamsForOrders()">筛选</a>
                    </label>
                </form>
            </div>
        </shiro:hasPermission>
        <table class="easyui-datagrid" id="order-list-grid" title="工单信息" cellpadding="10"
               data-options="singleSelect:true,collapsible:true,pagination:true">
        </table>
    </div>
    <div id="task-assignments" class="easyui-dialog" title="工单加工流程详情"
         data-options="closed:true,modal: true"
         style="width:700px;padding:5px;">
        <table class="easyui-datagrid" id="task-list-grid" title="工单流程信息" cellpadding="10"
               data-options="singleSelect:true,collapsible:true">
        </table>
    </div>
    <div id="priority-dialog" class="easyui-dialog" title="变更工单优先级"
         data-options="closed:true,modal: true"
         style="width:400px;padding:5px;">
        <form id="edit-priority-form" class="easyui-form" method="post"
              data-options="novalidate:true,ajax:true">
            <table>
                <tr>
                    <td style="font-size: 0.8rem;">加工优先级：</td>
                    <td><select class="easyui-combobox" style="width:173px;"
                                name="priority"
                                data-options="panelHeight:75,required:true,missingMessage:'加工优先级不能为空'">
                        <option value="0">正常</option>
                        <option value="1">急</option>
                        <option value="2">加急</option>
                    </select>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type="hidden" name="X_Requested_With" value="XMLHttpRequest">
                        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitChangePriority()">变更</a>
                    </td>
                </tr>
            </table>
        </form>
    </div>
    <script>
        var orderGrid = $('#order-list-grid');
        var taskGrid = $('#task-list-grid');
        var taskWindow = $('#task-assignments');
        var priorityDialog = $('#priority-dialog');
        var editPriorityForm = $('#edit-priority-form');
        window.deleteOrder = function (index) {
            if (!orderGrid.innerRows) {
                return;
            }
            var rows = orderGrid.innerRows.rows;
            var id = rows[index].orderId;
            var orderNumber = rows[index].orderNumber;
            $.messager.confirm("删除工单信息", "确定删除id为" + id + "，编号为" + orderNumber + "的工单？", function (r) {
                if (r) {
                    $.ajax({
                        url: "${pageContext.request.contextPath}/order/delete/" + id,
                        method: 'post',
                        success: function (res) {
                            res = typeof res == 'string' ? $.parseJSON(res) : res;
                            if (!res.error) {
                                $.messager.alert("删除工单信息", res.msg, 'info');
                                orderGrid.datagrid("reload");
                            } else {
                                $.messager.alert("删除工单信息", res.msg, 'error');
                            }
                        }
                    });
                }
            });
        };
        /**
         * 修改指定行的具体任务分配
         */
        window.editTask = function (index) {
            // 获取全局保存的工单列表
            window.__current_index = index;
            var result = window.__current_order_list_result;
            if (!result) {
                return;
            }
            var orderTasks = result.rows[index].orderTasks;
            window.__current_order_tasks = orderTasks;
            taskGrid.datagrid('loadData', {
                total: orderTasks.length,
                rows: orderTasks
            });
            // 修改任务表格的标题为工单号
            taskGrid.datagrid('getPanel').panel('setTitle', '工单号：' + result.rows[index].orderTaskNo);
            taskWindow.window({
                onClose: function () {
                    // 防止再次加载时处于已进入选择状态
                    var rows = taskGrid.datagrid('getRows');
                    for (var i = 0; i < rows.length; i++) {
                        taskGrid.datagrid('endEdit', index);
                    }
                }
            });
            taskWindow.window('open');
        };

        /**
         * 更改工单状态为清欠
         */
        window.payOrder = function (index) {
            if (!orderGrid.innerRows) {
                return;
            }
            var rows = orderGrid.innerRows.rows;
            var id = rows[index].orderId;
            var orderNumber = rows[index].orderNumber;
            var orderPaymentStatus = rows[index].orderPaymentStatus;
            if (orderPaymentStatus == 0) {
                $.messager.alert('工单[' + orderNumber + ']支付状态变更', '该工单已清欠', 'info');
                return;
            }
            $.messager.confirm('工单[' + orderNumber + ']支付状态变更',
                '确定将该工单的支付状态由未收更变为清欠？', function () {
                    $.ajax({
                        url: "${pageContext.request.contextPath}/order/" + id + '/paid',
                        method: 'post',
                        success: function (res) {
                            res = typeof res == 'string' ? $.parseJSON(res) : res;
                            if (!res.error) {
                                $.messager.alert('工单[' + orderNumber + ']支付状态变更', res.msg, 'info');
                                orderGrid.datagrid("reload");
                            } else {
                                $.messager.alert('工单[' + orderNumber + ']支付状态变更', res.msg, 'error');
                            }
                        }
                    });
                })
        };
        /**
         * 变更工单优先级
         */
        window.editPriority = function (index) {
            if (!orderGrid.innerRows) {
                return;
            }
            var rows = orderGrid.innerRows.rows;
            var id = rows[index].orderId;
            var orderNumber = rows[index].orderNumber;
            var priority = rows[index].orderPriority;
            editPriorityForm.form({
                url: window.projectPath + '/order/' + id + '/change-priority',
                success: function (data) {
                    data = $.parseJSON(data);
                    $.messager.progress('close');
                    if (!data.error) {
                        $.messager.alert('变更工单[' + orderNumber + ']工单优先级', data.msg, 'info', function () {
                            priorityDialog.dialog('close');
                            orderGrid.datagrid("reload");
                        });
                    } else {
                        $.messager.alert('变更工单[' + orderNumber + ']工单优先级', data.msg, "error");
                    }
                }, onLoadError: function () {
                    $.messager.progress('close');
                },
                onSubmit: function (param) {
                    var isOk = $(this).form('enableValidation').form('validate');
                    if (isOk) {
                        $.messager.progress({
                            title: '请稍候',
                            msg: '变更工单优先级中...'
                        });
                    }
                    return isOk;
                }
            });
            editPriorityForm.form('load', {
                priority: priority
            });
            priorityDialog.dialog({
                title: '变更工单[' + orderNumber + ']优先级'
            });
            priorityDialog.dialog('open');
        };
        window.submitChangePriority = function () {
            editPriorityForm.submit();
        };
        /**
         * 生产管理改变加工力度
         */
        window.editIsQuick = function (index) {
            if (!orderGrid.innerRows) {
                return;
            }
            var rows = orderGrid.innerRows.rows;
            var id = rows[index].orderId;
            var orderNumber = rows[index].orderNumber;
            var isQuick = rows[index].orderIsQuick;
            $.messager.prompt('变更工单[' + orderNumber + ']加工优先级',
                '当前工单加工优先级为:' + isQuick + '，请输入变更后的优先级:', function (r) {
                    if (r) {
                        var r = parseInt(r);
                        if (Number.isNaN(r)) {
                            $.messager.alert('变更工单[' + orderNumber + ']加工优先级', "请输入正确的优先级数字", 'info');
                        }
                        $.ajax({
                            url: "${pageContext.request.contextPath}/order/" + id + '/change-is-quick?isQuick='
                            + r,
                            method: 'post',
                            success: function (res) {
                                res = typeof res == 'string' ? $.parseJSON(res) : res;
                                if (!res.error) {
                                    $.messager.alert('变更工单[' + orderNumber + ']加工优先级', res.msg, 'info');
                                    orderGrid.datagrid("reload");
                                } else {
                                    $.messager.alert('变更工单[' + orderNumber + ']加工优先级', res.msg, 'error');
                                }
                            }
                        });
                    }
                });
        };
        /**
         * 客户编辑工单留言
         */
        window.editMessage = function (index) {
            if (!orderGrid.innerRows) {
                return;
            }
            var rows = orderGrid.innerRows.rows;
            var id = rows[index].orderId;
            var orderNumber = rows[index].orderNumber;
            $.messager.prompt('变更工单[' + orderNumber + ']留言', '输入您欲更变的留言：', function (msg) {
                if (msg) {
                    $.ajax({
                        url: "${pageContext.request.contextPath}/order/" + id + '/change-message?message='
                        + msg,
                        method: 'post',
                        success: function (res) {
                            res = typeof res == 'string' ? $.parseJSON(res) : res;
                            if (!res.error) {
                                $.messager.alert('变更工单[' + orderNumber + ']留言', res.msg, 'info');
                                orderGrid.datagrid("reload");
                            } else {
                                $.messager.alert('变更工单[' + orderNumber + ']留言', res.msg, 'error');
                            }
                        }
                    });
                }
            })
        };
        /**
         * 分配任务操作
         * @param index
         */
        window.distribution = function (index) {
            var row = taskGrid.datagrid('getRows')[index];
            var ed = taskGrid.datagrid('getEditor', {index: index, field: 'group'});
            if (ed && ed.target) {
                var value = $(ed.target).combobox('getValue');
                var text = $(ed.target).combobox('getText');
                var orderNo = row.taskNo;
                console.log(row);
                var taskName = row.taskProcess.processName;
                $.messager.confirm("分配工单[" + orderNo + "]的任务[" + taskName + "]", "确认分配到小组：" + text + "?", function (r) {
                    if (r) {
                        $.ajax({
                            url: window.projectPath + '/order/distribution/' + row.taskAssignmentId + '-' + value,
                            method: 'get',
                            success: function (res) {
                                res = typeof res == 'string' ? $.parseJSON(res) : res;
                                if (!res.error) {
                                    $.messager.alert({
                                        title: '分配任务流程：',
                                        msg: res.msg,
                                        icon: 'info'
                                    });
                                    orderGrid.datagrid({
                                        onLoadSuccess: function () {
                                            var result = window.__current_order_list_result;
                                            var orderTasks = result.rows[window.__current_index]
                                                .orderTasks;
                                            taskGrid.datagrid('loadData', {
                                                total: orderTasks.length,
                                                rows: orderTasks
                                            });
                                        }
                                    });
                                    orderGrid.datagrid("reload");
                                } else {
                                    $.messager.alert("分配任务流程：", res.msg, 'error');
                                }
                            }
                        });
                    }
                });
            }
            if (!ed || !ed.target || value == "") {
                taskGrid.datagrid('updateRow', {
                    index: index,
                    row: {
                        tip: '请先选择小组'
                    }
                })
            }
        };
        /**
         * 初始化任务流程表格
         */
        taskGrid.datagrid({
            columns: [[
                {field: 'taskAssignmentId', title: 'id'},
                {
                    field: 'taskProcess', title: '流程名',
                    formatter: function (value, row, index) {
                        return value.processName
                    }
                },
                {
                    field: 'taskWorkerGroupId', title: '是否分配',
                    formatter: function (value, row, index) {
                        if (value) {
                            return '是';
                        } else {
                            return '否';
                        }
                    }
                },
                {
                    field: 'taskStatus', title: '状态',
                    formatter: function (value, row, index) {
                        switch (value) {
                            case 0:
                                return '完工在库';
                            case -1: {
                                if (row.taskWorkerGroupId) {
                                    return '进行中';
                                } else {
                                    return '未分配';
                                }
                            }
                            default :
                                return '未知状态';
                        }
                    }
                }, {
                    title: '选择欲分配的小组', field: 'group', width: 200,
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'groupId',
                            textField: 'groupInfo',
                            loadFilter: function (data) {
                                if (!data.error) {
                                    for (var i = 0; i < data.list.length; i++) {
                                        var list = data.list[i];
                                        data.list[i].groupInfo = '组长:' + list.userRealName + '[' +
                                            list.userLoginName + ']' + '[人数:' +
                                            list.groupSize + ']';
                                    }
                                    return data.list;
                                } else {
                                    if (data.error == 404) {
                                        return [{
                                            groupInfo: '没有符合条件的工人小组'
                                        }];
                                    }
                                    $.messager.alert('加载错误', '加载角色出错!' + data.msg, 'error');
                                    return [];
                                }
                            }
                        }
                    },
                    formatter: function (value, row, index) {
                        if (row.taskWorkerGroupId) {
                            var groupId = row.taskWorkerGroupId;
                            var message = '已分配';
                            $.ajax({
                                url: window.projectPath + '/user/worker-group/captain/' + groupId,
                                method: 'get',
                                async: false,
                                success: function (res) {
                                    res = typeof res == 'string' ? $.parseJSON(res) : res;
                                    if (!res.error) {
                                        var captain = res.captain;
                                        message = message + ':' + captain.userRealName + '[' + captain.userLoginName + ']' + '[' + captain.groupSize + ']'
                                    }
                                }
                            });
                            if (row.taskStatus == 0) {
                                return '<span class="disabled">' + message + '</span>';
                            }
                            return message;
                        } else {
                            return '单击选择';
                        }
                    }
                }, {
                    field: 'option', title: '操作',
                    formatter: function (value, row, index) {
                        if (row.taskWorkerGroupId && row.taskStatus == 0) {
                            return '<a href="javascript:;" class="text-normal disabled">分配</a>'
                        }
                        return '<a href="javascript:;" class="text-normal" onclick="distribution(' + index + ')">分配</a>'
                    }
                }, {
                    field: 'tip', title: '提示', width: 200
                }
            ]],
            /**
             * 绑定单击事件以选择分配对象
             * @param index
             * @param field
             * @param value
             */
            onClickCell: function (index, field, value) {
                var row = $(this).datagrid('getRows')[index];
                // console.log(row);
                if (field == 'group' && row.taskStatus != 0) {
                    $(this).datagrid('beginEdit', index);
                    var ed = $(this).datagrid('getEditor', {index: index, field: field});
                    var orderTasks = window.__current_order_tasks;
                    var processId = orderTasks[index].taskProcessId;
                    $(ed.target).combobox('reload', window.projectPath + '/user/worker-group/captains/list/' + processId);
                    $(ed.target).focus();
                }
            }
        });
        window.submitParamsForOrders = function () {
            var paidbox = $('#search-paid');
            var statusbox = $('#search-order-status');
            var paid = paidbox.textbox("getValue");
            var status = statusbox.combobox("getValue");
            orderGrid.datagrid({
                queryParams: {
                    orderPaymentStatus: paid,
                    orderStatus: status
                }
            });
            orderGrid.datagrid("reload");
        };
        /**
         * 初始化工单表格
         */
        orderGrid.datagrid({
            rowStyler: function (index, row) {
                if (row.orderStatus == 4) {
                    return 'color:#ccc;';
                } else if (row.orderPriority == 1) {
                    return 'background:#DBAF38;';
                } else if (row.orderPriority >= 2) {
                    return 'background:#D3583C;color:white';
                }
            },
            url: window.projectPath + "/order/list",
            method: 'get',
            loadFilter: function (data) {
                // console.log(data);
                var result = {
                    rows: [],
                    total: 0
                };
                if (!data.error) {
                    result.total = data.pageInfo.total;
                    result.rows = data.pageInfo.list;
                    window.__current_order_list_result = result;
                } else {
                    if (data.error == 404) {
                        $.messager.alert('提示', '暂时没有与您相关的工单', 'info');
                    } else {
                        $.messager.alert('加载错误', '加载工单列表出错!' + data.msg, 'error');
                    }
                }
                orderGrid.innerRows = result;
                return result;
            },
            columns: [[
                {field: 'orderNumber', title: '工单号'},
                {
                    field: 'orderAddTime', title: '生成时间',
                    formatter: function (value, row, index) {
                        var date = new Date(value);
                        return date.format('yyyy-MM-dd hh:mm:ss');
                    }
                },
                {
                    field: 'orderPaymentStatus', title: '工单支付状态',
                    formatter: function (value, row, index) {
                        switch (value) {
                            default:
                            case -1:
                                return "未收:￥" + row.orderPrice + '\
                            <shiro:hasRole name="clerk">\
                                 <a href="javascript:;" style="color: #005;" onclick="payOrder(' + index + ')" >已付款？</a>\
                               </shiro:hasRole>';
                            case 0:
                                return "清欠:￥" + row.orderPrice;
                        }
                    }
                },
                {
                    field: 'orderPriority', title: '工单优先级',
                    formatter: function (value, row, index) {
                        var msg;
                        switch (value) {
                            case 0:
                                msg = "正常";
                                break;
                            case 1:
                                msg = "急";
                                break;
                            case 2:
                                msg = "加急";
                                break;
                            default:
                                msg = "未知优先级：" + value;
                                break;
                        }
                        var moreClass = '';
                        if (row.orderStatus == 4) {
                            moreClass = ' disabled';
                        }
                        return msg + ' <shiro:hasPermission name="smanager:admin">\
                                    <a href="javascript:;" class="' + moreClass + '" style="color: #005;" onclick="editPriority(' + index + ')" >(变更)</a>\
                                </shiro:hasPermission>';
                    }
                },
                {
                    field: 'orderIsQuick', title: '加工优先级',
                    formatter: function (value, row, index) {
                        var moreClass = '';
                        if (row.orderStatus == 4) {
                            moreClass = ' disabled';
                        }
                        return value + ' <shiro:hasPermission name="pmanager:admin">\
                                    <a href="javascript:;" class="' + moreClass + '" style="color: #005;" onclick="editIsQuick(' + index + ')" >(变更)</a>\
                                </shiro:hasPermission>';
                    }
                },
                {
                    field: 'orderTasksProcess', title: '工单加工流程',
                    formatter: function (tasks, row, index) {
                        var taskNames = [];
                        for (var i = 0; i < row.orderTasks.length; i++) {
                            if (row.orderTasks[i].taskProcess.processName == '镀钛') {
                                // 显示镀金颜色（若有）
                                if (row.orderProductionColor) {
                                    taskNames.push(row.orderTasks[i].taskProcess.processName + '[' + row.orderProductionColor + ']');
                                    continue;
                                }
                            }
                            taskNames.push(row.orderTasks[i].taskProcess.processName);
                        }
                        return taskNames.toString();
                    }
                },
                {
                    field: 'orderTasks', title: '当前进度',
                    formatter: function (tasks, row, index) {
                        var currentTask = {
                            task: {
                                taskStatus: -2,
                                taskProcess: {
                                    processName: '未开始'
                                }
                            },
                            priority: 9999
                        };
                        for (var i = 0; i < tasks.length; i++) {
                            if (tasks[i].taskProcess.processPriority < currentTask.priority &&
                                tasks[i].taskStatus == 0
                            ) {
                                currentTask.priority = tasks[i].taskProcess.processPriority;
                                currentTask.task = tasks[i];
                            }
                        }
                        if (currentTask.task.taskStatus == -2) {
                            if (tasks[0].taskWorkerGroupId) {
                                currentTask.task = tasks[0];
                            }
                        }
                        switch (currentTask.task.taskStatus) {
                            case -2:
                                return currentTask.task.taskProcess.processName;
                            case -1:
                                return currentTask.task.taskProcess.processName + "：进行中";
                            case 0:
                                return currentTask.task.taskProcess.processName + "：已完成";
                            default:
                                return "未知"
                        }
                    }
                },
                {
                    field: 'orderStatus', title: '工单状态',
                    formatter: function (value, row, index) {
                        switch (value) {
                            case 0:
                                return "未做";
                            case 1:
                                return "在库";
                            case 2:
                                return "完工";
                            case 3:
                                return "已发";
                            case 4:
                                return "已完成";
                            default:
                                return "未知状态:" + value
                        }
                    }
                },
                {
                    field: 'option', title: '操作',
                    formatter: function (value, row, index) {
                        var moreClass = '';
                        if (row.orderStatus == 4) {
                            moreClass = ' disabled';
                        }
                        return '\
                         <shiro:hasPermission name="order:edit">\
                                <a href="javascript:;" style="color: #005;" class="' + moreClass + '" onclick="editTask(' + index + ')" >订单任务分配</a>\
                                </shiro:hasPermission>\
                                <shiro:hasRole name="customer">\
                                    <a href="javascript:;" style="color: #005;" class="' + moreClass + '" onclick="editMessage(' + index + ')" >变更留言</a>\
                                </shiro:hasRole>\
                                <shiro:hasRole name="customer_special">\
                                    <a href="javascript:;" style="color: #005;" class="' + moreClass + '" onclick="editMessage(' + index + ')" >变更留言</a>\
                                </shiro:hasRole>\
                                <shiro:hasRole name="admin">\
                                <a href="javascript:;" style="color: #005;"  onclick="deleteOrder(' + index + ')">删除该工单</a>\
                               </shiro:hasRole>';
                    }
                }
            ]]
        });
    </script>
</div>